﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Windows8Accelerator.Core.Xaml.Html;

namespace Windows8Accelerator.Core.Xaml.Controls.RichText
{
    public class TextVisitor : ContentVisitor
    {
        public TextVisitor(SuperHtmlNode superHtmlNode, SuperHtmlNodeVisitor parentVisitor)
            : base(superHtmlNode, parentVisitor)
        {
            VisitChildren = false;
        }

        protected override void InternalVisitNode1(SuperHtmlNode htmlNode)
        {
            var text = htmlNode.Text;
            var leadingSpace = "";

            if (((text.StartsWith(" ") ||
                text.StartsWith("\r") ||
                text.StartsWith("\n") ||
                text.StartsWith("\t")) && State.AllowLeadingSpace) || (State.RequiresLeadingSpace && State.HasContent))
                leadingSpace = " ";

            text = Trim(text);

            if (text.Length > 0)
            {
                if (AddLineBreakingIfNecessary())
                {
                    leadingSpace = "";
                }

                text = WebUtility.HtmlDecode(text);
                if (!text.StartsWith(" "))
                    text = leadingSpace + text;
                AddRun(text);
            }

            if ((htmlNode.Text.EndsWith(" ") ||
                htmlNode.Text.EndsWith("\r") ||
                htmlNode.Text.EndsWith("\n") ||
                htmlNode.Text.EndsWith("\t")))
                State.RequiresLeadingSpace = true;
            else
                State.RequiresLeadingSpace = false;


        }
    }
}
